﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Utilities
{
    public enum MsgType
    {
        LoginMessage        = 0,
        LoginResultMessage  = 1,
        LogoutMessage       = 2,
    }

    public class Msg
    {
        public const int USER_MAX_LENGTH = 40;
        public const int PASSWORD_MAX_LENGTH = 40;
        public const int MESSAGE_LENGTH = 1024;


        public MsgType MesageType = MsgType.LoginMessage;
        public string strUser;
        public string strPassword;

        public byte[] ToByteArray()
        {
            byte[] result = new byte[MESSAGE_LENGTH];
            result[0] = (byte)MesageType;

            byte[] aUser = Encoding.UTF8.GetBytes(strUser + "\n");
            byte[] aPassword = Encoding.UTF8.GetBytes(strPassword + "\n");

            for (int i = 0; i < aUser.Length; i++)
            {
                result[i + 1] = aUser[i];
            }
            
            for (int i = 0; i < aPassword.Length; i++)
            {
                result[i + USER_MAX_LENGTH + 1] = aPassword[i];
            }
            return result;
        }

        public static Msg GetLoginMessage(byte[] byteArray)
        {
            Msg msg = new Msg();
            msg.MesageType = MsgType.LoginMessage;
            string strUser = Encoding.UTF8.GetString(byteArray, 1, USER_MAX_LENGTH);
            strUser = strUser.Split('\n')[0];
            msg.strUser = strUser;

            string strPassword = Encoding.UTF8.GetString(byteArray, 1 + USER_MAX_LENGTH, PASSWORD_MAX_LENGTH);
            strPassword = strPassword.Split('\n')[0];
            msg.strPassword = strPassword;

            return msg;
        }
    }
}
